<template>
  <div class="blog-editor-view">
    <el-card>
      <template #header>
        <div class="header">
          <h2>{{ isEdit ? '编辑文章' : '写文章' }}</h2>
          <div class="actions">
            <el-button @click="handleCancel">取消</el-button>
            <el-button @click="handleSaveDraft">保存草稿</el-button>
            <el-button type="primary" @click="handlePublish">发布文章</el-button>
          </div>
        </div>
      </template>

      <el-form
        ref="formRef"
        :model="form"
        :rules="rules"
        label-width="80px"
        class="blog-form"
      >
        <el-form-item label="标题" prop="title">
          <el-input
            v-model="form.title"
            placeholder="请输入文章标题"
            maxlength="100"
            show-word-limit
          />
        </el-form-item>

        <el-form-item label="分类" prop="category">
          <el-select
            v-model="form.category"
            placeholder="请选择文章分类"
            class="category-select"
          >
            <el-option
              v-for="item in categories"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            />
          </el-select>
        </el-form-item>

        <el-form-item label="标签" prop="tags">
          <el-select
            v-model="form.tags"
            multiple
            filterable
            allow-create
            default-first-option
            placeholder="请选择或输入标签"
            class="tag-select"
          >
            <el-option
              v-for="item in tags"
              :key="item"
              :label="item"
              :value="item"
            />
          </el-select>
        </el-form-item>

        <el-form-item label="摘要" prop="summary">
          <el-input
            v-model="form.summary"
            type="textarea"
            :rows="3"
            placeholder="请输入文章摘要"
            maxlength="200"
            show-word-limit
          />
        </el-form-item>

        <el-form-item label="封面">
          <el-upload
            class="cover-uploader"
            :show-file-list="false"
            :before-upload="beforeCoverUpload"
            :http-request="uploadCover"
          >
            <el-image
              v-if="form.cover"
              :src="form.cover"
              fit="cover"
              class="cover-image"
            />
            <el-icon v-else class="cover-uploader-icon"><Plus /></el-icon>
          </el-upload>
        </el-form-item>

        <el-form-item label="内容" prop="content" class="content-item">
          <div class="editor-toolbar">
            <el-button-group>
              <el-button @click="insertText('**', '**')">加粗</el-button>
              <el-button @click="insertText('*', '*')">斜体</el-button>
              <el-button @click="insertText('### ', '')">标题</el-button>
              <el-button @click="insertText('> ', '')">引用</el-button>
              <el-button @click="insertText('`', '`')">代码</el-button>
              <el-button @click="insertText('\n```\n', '\n```\n')">代码块</el-button>
              <el-button @click="insertText('- ', '')">列表</el-button>
              <el-button @click="insertLink">链接</el-button>
              <el-button @click="uploadImage">图片</el-button>
            </el-button-group>
          </div>

          <div class="editor-container">
            <el-input
              v-model="form.content"
              type="textarea"
              :rows="20"
              placeholder="请输入文章内容（支持 Markdown 格式）"
              @input="handleContentChange"
            />
            
            <div class="preview markdown-body" v-html="renderedContent" />
          </div>
        </el-form-item>
      </el-form>
    </el-card>
  </div>
</template>

<script setup lang="ts">
import { ref, computed, onMounted } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { ElMessage, ElMessageBox, type FormInstance } from 'element-plus'
import { Plus } from '@element-plus/icons-vue'
import { marked } from 'marked'
import hljs from 'highlight.js'
import { useBlogStore } from '@/stores/blog'
import { uploadImage as uploadImageApi } from '@/utils/upload'
import type { Blog } from '@/types'

const route = useRoute()
const router = useRouter()
const blogStore = useBlogStore()

// 表单相关
const formRef = ref<FormInstance>()
const form = ref<Partial<Blog>>({
  title: '',
  category: '',
  tags: [],
  summary: '',
  content: '',
  cover: ''
})

// 校验规则
const rules = {
  title: [
    { required: true, message: '请输入文章标题', trigger: 'blur' },
    { min: 2, max: 100, message: '标题长度在 2 到 100 个字符', trigger: 'blur' }
  ],
  category: [
    { required: true, message: '请选择文章分类', trigger: 'change' }
  ],
  tags: [
    { required: true, message: '请至少选择一个标签', trigger: 'change' },
    { type: 'array', max: 5, message: '最多选择 5 个标签', trigger: 'change' }
  ],
  summary: [
    { required: true, message: '请输入文章摘要', trigger: 'blur' },
    { max: 200, message: '摘要最多 200 个字符', trigger: 'blur' }
  ],
  content: [
    { required: true, message: '请输入文章内容', trigger: 'blur' },
    { min: 50, message: '内容至少 50 个字符', trigger: 'blur' }
  ]
}

// 分类和标签数据
const categories = ref([
  { label: '技术', value: 'tech' },
  { label: '生活', value: 'life' },
  { label: '随笔', value: 'essay' },
  { label: '其他', value: 'other' }
])

const tags = ref([
  'Vue', 'React', 'TypeScript', 'JavaScript', 'Node.js',
  'Python', '前端', '后端', '数据库', '算法'
])

// 编辑状态
const isEdit = computed(() => Boolean(route.params.id))

// Markdown 预览
const renderedContent = computed(() => {
  if (!form.value.content) return ''
  return marked(form.value.content, {
    highlight: (code, lang) => {
      if (lang && hljs.getLanguage(lang)) {
        return hljs.highlight(code, { language: lang }).value
      }
      return hljs.highlightAuto(code).value
    }
  })
})

// 方法
const insertText = (prefix: string, suffix: string) => {
  const textarea = document.querySelector('.editor-container textarea')
  if (!textarea) return
  
  const start = textarea.selectionStart
  const end = textarea.selectionEnd
  const text = form.value.content || ''
  
  const beforeText = text.substring(0, start)
  const selectedText = text.substring(start, end)
  const afterText = text.substring(end)
  
  form.value.content = beforeText + prefix + selectedText + suffix + afterText
  
  // 恢复光标位置
  setTimeout(() => {
    textarea.focus()
    textarea.setSelectionRange(
      start + prefix.length,
      end + prefix.length
    )
  })
}

const insertLink = () => {
  ElMessageBox.prompt('请输入链接地址', '插入链接', {
    inputPattern: /^(https?:\/\/)?([\da-z.-]+)\.([a-z.]{2,6})([/\w .-]*)*\/?$/,
    inputErrorMessage: '请输入有效的URL'
  }).then(({ value }) => {
    insertText('[链接文字](', value + ')')
  })
}

const uploadImage = async () => {
  const input = document.createElement('input')
  input.type = 'file'
  input.accept = 'image/*'
  
  input.onchange = async (e: Event) => {
    const file = (e.target as HTMLInputElement).files?.[0]
    if (!file) return
    
    try {
      const url = await uploadImageApi(file)
      insertText('![图片](', url + ')')
    } catch (error) {
      console.error('Failed to upload image:', error)
      ElMessage.error('图片上传失败')
    }
  }
  
  input.click()
}

const beforeCoverUpload = (file: File) => {
  const isImage = file.type.startsWith('image/')
  const isLt2M = file.size / 1024 / 1024 < 2

  if (!isImage) {
    ElMessage.error('只能上传图片文件')
    return false
  }
  if (!isLt2M) {
    ElMessage.error('图片大小不能超过 2MB')
    return false
  }
  return true
}

const uploadCover = async ({ file }: { file: File }) => {
  try {
    const url = await uploadImageApi(file)
    form.value.cover = url
    ElMessage.success('封面上传成功')
  } catch (error) {
    console.error('Failed to upload cover:', error)
    ElMessage.error('封面上传失败')
  }
}

const handleContentChange = () => {
  // 可以在这里添加自动保存逻辑
}

const handleCancel = () => {
  ElMessageBox.confirm('确定要取消编辑吗？未保存的内容将会丢失', '提示', {
    type: 'warning'
  }).then(() => {
    router.back()
  })
}

const handleSaveDraft = async () => {
  await saveBlog('draft')
}

const handlePublish = async () => {
  await saveBlog('published')
}

const saveBlog = async (status: 'draft' | 'published') => {
  if (!formRef.value) return
  
  try {
    await formRef.value.validate()
    
    const blogData = {
      ...form.value,
      status
    }
    
    if (isEdit.value) {
      await blogStore.updateBlog(Number(route.params.id), blogData)
    } else {
      await blogStore.createBlog(blogData)
    }
    
    ElMessage.success(status === 'published' ? '发布成功' : '保存成功')
    router.push('/')
  } catch (error) {
    console.error('Failed to save blog:', error)
    ElMessage.error(status === 'published' ? '发布失败' : '保存失败')
  }
}

// 获取文章数据（编辑模式）
const fetchBlogData = async () => {
  if (!isEdit.value) return
  
  try {
    await blogStore.fetchBlogDetail(Number(route.params.id))
    if (blogStore.currentBlog) {
      form.value = { ...blogStore.currentBlog }
    }
  } catch (error) {
    console.error('Failed to fetch blog:', error)
    ElMessage.error('获取文章数据失败')
    router.push('/')
  }
}

onMounted(() => {
  fetchBlogData()
})
</script>

<style lang="scss" scoped>
.blog-editor-view {
  .header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    
    h2 {
      margin: 0;
    }
    
    .actions {
      display: flex;
      gap: 10px;
    }
  }
  
  .blog-form {
    .category-select,
    .tag-select {
      width: 100%;
      max-width: 400px;
    }
    
    .cover-uploader {
      :deep(.el-upload) {
        border: 1px dashed #d9d9d9;
        border-radius: 6px;
        cursor: pointer;
        position: relative;
        overflow: hidden;
        transition: border-color 0.3s;
        
        &:hover {
          border-color: $primary-color;
        }
      }
      
      .cover-uploader-icon {
        font-size: 28px;
        color: #8c939d;
        width: 200px;
        height: 120px;
        line-height: 120px;
        text-align: center;
      }
      
      .cover-image {
        width: 200px;
        height: 120px;
        display: block;
      }
    }
    
    .content-item {
      .editor-toolbar {
        margin-bottom: 10px;
      }
      
      .editor-container {
        display: grid;
        grid-template-columns: 1fr 1fr;
        gap: 20px;
        
        .el-textarea {
          font-family: monospace;
        }
        
        .preview {
          border: 1px solid #dcdfe6;
          border-radius: 4px;
          padding: 15px;
          overflow-y: auto;
          background-color: #fff;
        }
      }
    }
  }
}

// 响应式布局
@media (max-width: $breakpoint-md) {
  .blog-editor-view {
    .blog-form {
      .content-item {
        .editor-container {
          grid-template-columns: 1fr;
          
          .preview {
            display: none;
          }
        }
      }
    }
  }
}
</style>